<?php

namespace yunj\command;

use think\console\Input;
use think\console\Output;
use yunj\core\Command as BaseCommand;

class RedisClear extends BaseCommand {

    protected function configure() {
        $this->setName('yunj:redis-clear')
            ->setDescription('云静系统Redis缓存清理');
    }

    protected function execute(Input $input, Output $output) {
        ini_set("display_errors", "On");//打开错误提示
        ini_set("error_reporting", E_ALL);//显示所有错误
        set_time_limit(3600);

        try {
            $redis = redis();
            $prefix = config('cache.stores.redis.prefix');
            if (!$prefix) {
                throw new \RuntimeException('未配置redis前缀，config/cache.php => stores.redis.prefix');
            }
            $iterator = null;
            do {
                // 使用 SCAN 命令迭代匹配的 key
                $keys = $redis->scan($iterator, $prefix . '*');
                if ($keys) {
                    $redis->del($keys);
                }
            } while ($iterator);
            $this->success();
        } catch (\Throwable $e) {
            $errMsg = $e instanceof \RuntimeException ? $e->getMessage() : exception_to_str($e);
            $this->error($errMsg);
        }
    }
}